#pragma once

#include <iostream>
#include <unordered_map>
#include <functional>
#include <ctime>
#include <unistd.h>


using task_t = std::function<void()>;

// mimic task
void DownLoad(){
    std::cout << "下载任务" << std::endl;
    sleep(1);
}

void Log(){
    std::cout << "日志任务" << std::endl;
    sleep(1);
}

void Sql(){
    std::cout << "数据库任务" << std::endl;
    sleep(1);
}

static int number = 0;
class TaskManager{
public:
    // ��������ֻ��Ҫ����һ��TaskManager��ͺ�
    TaskManager(){
        srand(time(nullptr));
        InsertTask(DownLoad);
        InsertTask(Log);
        InsertTask(Sql);
    }

    void InsertTask(task_t t){
        tasks[number++] = t;
    }

    // ѡ������1.roundrobin 2.pseudo-random 
    int SelectTask(){
        return rand() % tasks.size();
    }

    
    ~TaskManager(){}

    void Execute(int num){
        if(tasks.find(num) == tasks.end()) return;
        tasks[num]();
    }
private:
    std::unordered_map<int,task_t> tasks;
}/*tm*/;

TaskManager tm; //����ֱ��д����� ��Cpp����C�� �����Ƽ�������ֱ��������ֱ�ۡ�

void Worker()
{
    while (true)
    {
        // 写的时候四字节 读也是 因为都是int类型
        int cmd = 0;
        int n = ::read(0, &cmd, sizeof(cmd));
        if (n == 0)
        {
            std::cout << "pid: " << getpid() << "quit ..." << std::endl;
            break; // 退出
        }
        if (n == sizeof(cmd))
        {
            // 读到四个字节 执行任务
            tm.Execute(cmd);
        }
        else if (n < 0)
            exit(1);
    }
}
